/*******************************************************************************
* Copyright (c) 2010, 2018 西安秦晔信息科技有限公司
* Licensed under the Apache License, Version 2.0 (the "License");
*    you may not use this file except in compliance with the License.
*    You may obtain a copy of the License at
*
*       http://www.apache.org/licenses/LICENSE-2.0
*
*    Unless required by applicable law or agreed to in writing, software
*    distributed under the License is distributed on an "AS IS" BASIS,
*    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*    See the License for the specific language governing permissions and
*    limitations under the License.
*******************************************************************************/
package com.qinyeit.serviceapp.service.stores.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.qinyeit.serviceapp.entity.*;
import com.qinyeit.serviceapp.entity.enums.PaymentState;
import com.qinyeit.serviceapp.entity.enums.ReceivePaymentType;
import com.qinyeit.serviceapp.entity.enums.StoreInState;
import com.qinyeit.serviceapp.entity.enums.StoreInType;
import com.qinyeit.serviceapp.exception.BusinessRunTimeException;
import com.qinyeit.serviceapp.repository.stores.StoreInOrderDetailRepository;
import com.qinyeit.serviceapp.repository.stores.StoreInOrderRepository;
import com.qinyeit.serviceapp.service.dishes.DishesStoreService;
import com.qinyeit.serviceapp.service.materials.PurchaseSpecService;
import com.qinyeit.serviceapp.service.stores.ReceivePaymentDetailService;
import com.qinyeit.serviceapp.service.stores.ReceivePaymentService;
import com.qinyeit.serviceapp.service.stores.StockService;
import com.qinyeit.serviceapp.service.stores.StoreInOrderService;
import com.qinyeit.serviceapp.utils.CompuUtils;
import com.qinyeit.serviceapp.utils.LocalUtils;
import com.qinyetech.springstage.core.date.DateUtils;
import com.qinyetech.springstage.core.service.BaseService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.http.auth.BasicUserPrincipal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

/** 
 * ClassName: StoreInOrderServiceImpl <br/> 
 * Function: 入库单据 业务实现 <br/> 
 * date: 2018-11-08 14:01:15 <br/> 
 * 
 * @author liuwenjin
 * @version 1.0
 * @since JDK 1.8
 */
@Service
@Transactional
public class StoreInOrderServiceImpl extends BaseService<StoreInOrder, Long> implements StoreInOrderService {


	@Autowired
	private StoreInOrderRepository storeInOrderRepository;
	@Autowired
	private PurchaseSpecService purchaseSpecService;
	@Autowired
	private StoreInOrderDetailRepository storeInOrderDetailRepository;

	@Autowired
	private StockService stockService;
	@Autowired
	private DishesStoreService dishesStoreService;
	@Autowired
	private ReceivePaymentService receivePaymentService;
	@Autowired
	private ReceivePaymentDetailService receivePaymentDetailService;




	@Override
	public void saveData(JSONObject data, Long merchantGroupId,String operator) {

		log.info("data -- {}",data);

		JSONObject orderData = data.getJSONObject("storeInOrder");

		if(orderData==null){
			throw new BusinessRunTimeException("订单信息为空",10002);
		}

		/*if(orderData.getLong("supplierId")==null){
			throw new BusinessRunTimeException("请选择供应商，供应商不能为空",100001);
		}*/
		if(orderData.getLong("warehouseId")==null){
			throw new BusinessRunTimeException("请选择入库仓库，仓库不能为空",10002);
		}

		JSONArray detailData = data.getJSONArray("details");
		if(CollectionUtils.isEmpty(detailData)){
			throw new BusinessRunTimeException("订单明细为空",10002);
		}
		Long id = orderData.getLong("id");
		int type = data.getInteger("type");
		double amountSum=0.0;
		StoreInOrder storeInOrder = null;
		if(id!=null){
			storeInOrder = this.findById(id);
			//编辑
//			删除以前的数据
			storeInOrderRepository.deleteOrderDetails(id,merchantGroupId);
		}else {
			storeInOrder = new StoreInOrder();
			storeInOrder.setNo(LocalUtils.getOrderNo());
		}
		storeInOrder.setType(StoreInType.valueOf(orderData.getString("type")));
		if(type==1){ //保存
			storeInOrder.setState(StoreInState.NOAUDIT);
		}else if(type==2){
			//提交并审核
			storeInOrder.setState(StoreInState.AUDIT);
		}
		storeInOrder.setInTime(DateUtils.date());
		storeInOrder.setWarehouseId(orderData.getLong("warehouseId"));
		storeInOrder.setWarehouseName(orderData.getString("warehouseName"));
		storeInOrder.setSupplierId(orderData.getLong("supplierId"));
		storeInOrder.setSupplierName(orderData.getString("supplierName"));
		DishesStore store = dishesStoreService.findById(orderData.getLong("storeId"));
		storeInOrder.setStoreId(orderData.getLong("storeId"));
		storeInOrder.setStoreName(store.getName());
		storeInOrder.setOperatorName(operator);

		JSONObject item;
		PurchaseSpec spec = null;
		StoreInOrderDetail detail = null;
		List<StoreInOrderDetail> detailList = Lists.newArrayList();
		for (int i = 0; i < detailData.size(); i++) {
			item = detailData.getJSONObject(i);
			spec = purchaseSpecService.findById(item.getLong("specId"));
			detail = new StoreInOrderDetail();
			detail.setOrder(storeInOrder);
			detail.setMaterialId(item.getLong("materialId"));
			detail.setNo(item.getString("no"));
			detail.setName(item.getString("name"));
			detail.setSpecId(item.getLong("specId"));
			detail.setSpec(spec.getMaterial().getGoodsSpec());
			detail.setUnit(spec.getMaterial().getUnit());
			detail.setPurchaseSpec(spec.getName());
			detail.setPurchaseUnit(spec.getUnit());
			detail.setCreateAt(DateUtils.date());
			detail.setCode(spec.getMaterial().getCode());
			if(type==1){
				//保存
				detail.setCount(item.getDouble("count"));
				detail.setPrice(item.getDouble("price"));
				detail.setTotal(CompuUtils.multiply(item.getDouble("count"),item.getDouble("price")));

			}else if(type==2){
				//提交并审核
				detail.setStorageCount(item.getDouble("count")*spec.getRatio());
				detail.setStoragePrice(item.getDouble("price")/spec.getRatio());
				detail.setStorageTotal(CompuUtils.multiply(detail.getStorageCount(),detail.getStoragePrice()));
				detail.setStorageUnit(spec.getMaterial().getUnit());
				detail.setCount(item.getDouble("count"));
				detail.setPrice(item.getDouble("price"));
				detail.setTotal(CompuUtils.multiply(item.getDouble("count"),item.getDouble("price")));
				//保存最新一次进货价格
				spec.setHistoryPrice(item.getDouble("price"));
				spec = purchaseSpecService.update(spec);

				log.info("--------------------最近采购价格" + spec.getHistoryPrice());

			}
			detail.setMerchantGroupId(merchantGroupId);
			detailList.add(detail);
			amountSum = CompuUtils.add(amountSum,detail.getTotal());
		}

		storeInOrderDetailRepository.saveAll(detailList);
		storeInOrder.setAmount(amountSum);
		storeInOrder.setMerchantGroupId(merchantGroupId);

		storeInOrder.setPayAmount(orderData.getDouble("payAmount"));
		storeInOrder.setGiftAmount(orderData.getDouble("giftAmount"));
		double cha = CompuUtils.add(2,amountSum,orderData.getDouble("payAmount")*(-1),orderData.getDouble("giftAmount")*(-1));
		if(cha<0){
			throw new BusinessRunTimeException("实付金额不能大于订单总金额",10002);
		}
		if(cha==0){
			storeInOrder.setPaymentState(PaymentState.SETTLED);
		}else {
			storeInOrder.setPaymentState(PaymentState.NORMAL);
		}
		storeInOrder = this.update(storeInOrder);
		if (storeInOrder.getState()==StoreInState.AUDIT){
			//已审核 保存库存
			//保存库存
			stockService.saveStore(storeInOrder,detailList);
			//收款单
			if(CompuUtils.compareTo(storeInOrder.getPayAmount(),0)>0){
				saveReceivePaymentOrders(storeInOrder);
			}
		}




	}

	/**
	 * 保存收款单
	 * @param storeInOrder
	 */
	@Override
	public void saveReceivePaymentOrders(StoreInOrder storeInOrder) {
		ReceivePayment payment = new ReceivePayment();
		payment.setRemark(storeInOrder.getRemark());
		payment.setGiftAmount(storeInOrder.getGiftAmount());
		payment.setAmount(storeInOrder.getAmount());
		payment.setType(ReceivePaymentType.STOREIN);
		payment.setMerchantGroupId(storeInOrder.getMerchantGroupId());
		payment.setOperatorName(storeInOrder.getOperatorName());
		payment.setOperatorTime(DateUtils.date());
		payment.setSupplierName(storeInOrder.getSupplierName());
		payment.setSupplierId(storeInOrder.getSupplierId());
		payment.setNo(LocalUtils.getOrderNo());

		ReceivePaymentDetail detail = new ReceivePaymentDetail();
		detail.setRemark(storeInOrder.getRemark());
		detail.setPaymentState(storeInOrder.getPaymentState());
		detail.setGiftAmount(storeInOrder.getGiftAmount());
		detail.setAmount(storeInOrder.getPayAmount());
		detail.setOrderNo(storeInOrder.getNo());
		detail.setOrder(payment);
		detail.setOrderAmount(storeInOrder.getAmount());
		detail.setMerchantGroupId(storeInOrder.getMerchantGroupId());

		payment = receivePaymentService.save(payment);
		receivePaymentDetailService.save(detail);


	}

}